package com.oscarmovie.action;

import java.io.File;
import java.util.List;
import javax.servlet.ServletContext;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.oscarmovie.Constants;
import com.oscarmovie.model.Image;
import com.oscarmovie.model.Paging;
import com.oscarmovie.service.ImageService;

public class ImageAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	private ImageService imageService;
	private Image image = new Image();
	private List<Image> images;

	// for file uploading
	private File data;
	private String dataFileName;
	private String dataContentType;
	private Paging paging = new Paging();// 必须先初始化，因为有可能URL中不含Paging相关的信息，那即为NULL
	
	public String upload() throws Exception {
		ServletContext servletContext = (ServletContext)ActionContext.getContext().get(ServletActionContext.SERVLET_CONTEXT);
		String realPath = servletContext.getRealPath("");
		String suffixName = dataFileName.substring(dataFileName.lastIndexOf("."));
		String name = System.currentTimeMillis()+suffixName;
		File file = new File(realPath+"\\uploaded\\images\\" + name);
		FileUtils.copyFile(data, file);
		
		image.setData(name);
		return edit();
	}

	public String save() throws Exception {

		imageService.save(image);

		return edit();
	}

	public String load() throws Exception {

		if(image.getId()!=0)
		this.setImage(imageService.load(image.getId()));
		return SUCCESS;
	}

	public String add() throws Exception {
		setImage(new Image());
		return Constants.ADD;
	}

	public String edit() throws Exception {
		loadAll();
		load();
		return Constants.EDIT;
	}

	public String loadAll() throws Exception {
		this.images = imageService.loadAll(paging);
		return SUCCESS;
	}

	public String select() throws Exception {
		loadAll();
		return Constants.SELECT;
	}

	public List<Image> getImages() {
		return images;
	}

	public void setImageService(ImageService imageService) {
		this.imageService = imageService;
	}

	public void setImage(Image image) {
		this.image = image;
	}

	public Image getImage() {
		return image;
	}

	public void setData(File data) {
		this.data = data;
	}

	public File getData() {
		return data;
	}

	public void setDataFileName(String dataFileName) {
		this.dataFileName = dataFileName;
	}

	public String getDataFileName() {
		return dataFileName;
	}

	public void setDataContentType(String dataContentType) {
		this.dataContentType = dataContentType;
	}

	public String getDataContentType() {
		return dataContentType;
	}

	public void setPaging(Paging paging) {
		this.paging = paging;
	}

	public Paging getPaging() {
		return paging;
	}

}
